﻿using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Sdk;
using Xunit.Extensions;

namespace SubSpec
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
	public class ThesisAttribute : TheoryAttribute
	{
		protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method)
		{
			// prepare specification invocations  
			var theoryTestCommands = base.EnumerateTestCommands(method);

			var commands = new List<ITestCommand>();

			foreach (var item in theoryTestCommands)
			{
				if (item is TheoryCommand)
				{
					try
					{
						// Create a new test class instance
						object obj = Activator.CreateInstance(method.MethodInfo.ReflectedType);

						// create method
						item.Execute(obj);

						commands.AddRange(SpecificationContext.ToTestCommands(method));
					}

					catch (Exception ex)
					{
                        commands.Add( new ExceptionTestCommand( method, ex ) );
					}
				}
				else
				{
					commands.Clear();
					commands.Add(item);
					break;
				}
			}

			return commands;
		}
	}
}